package org.sxp.datax.executor.util;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.dialect.DriverUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.support.JdbcUtils;
import org.sxp.common.dto.DatabaseDTO;
import org.sxp.common.dto.TableNamesDTO;
import org.sxp.common.enums.DbTypeEnum;
import org.sxp.common.exception.DataAccessException;
import org.sxp.common.validator.ValidatorUtils;
import org.sxp.common.validator.group.MysqlGroup;
import org.sxp.common.validator.group.OracleGroup;

import javax.sql.DataSource;
import java.sql.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author shenxingping
 * @date 2021/12/30
 */
public class DbUtil {

    public static DriverManagerDataSource getDataSource(DatabaseDTO databaseDTO) throws Exception{
        try{
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setUsername(databaseDTO.getUsername());
            dataSource.setPassword(databaseDTO.getPassword());
            dataSource.setDriverClassName(DriverUtil.identifyDriver(databaseDTO.getUrl()));
            dataSource.setUrl(databaseDTO.getUrl());
            DriverManager.setLoginTimeout(3);
            return dataSource;
        }catch (Exception ex){
            throw new DataAccessException(ex);
        }
    }

    public static int excuteCUD(DatabaseDTO databaseDTO, String sql) throws Exception{
        DriverManagerDataSource dataSource = getDataSource(databaseDTO);
        try{
            return Db.use(dataSource).execute(sql.endsWith(";") ? sql.substring(0, sql.length()-1) : sql, null);
        }catch (Exception ex){
            throw new DataAccessException(ex);
        }
    }
}
